import os.path


class ClassPath:
    def __init__(self):
        self.boot = None
        self.ext = None
        self.user = None

    def _getJreOption(self, jreOption):
        if jreOption is not None and os.path.exists(jreOption):
            return jreOption

        if os.path.exists("./jre"):
            return "./jre"

        return os.path.join(os.getenv("JAVA_HOME"), "jre")

    def parseBootAndExtClassPath(self, jreOption):
        from classpath.wildcard_entry import WildcardEntry
        jreDir = self._getJreOption(jreOption)
        self.boot = WildcardEntry.newWildcardEntry(os.path.join(jreDir, "lib", "*"))
        self.ext = WildcardEntry.newWildcardEntry(os.path.join(jreDir, "lib", "ext", "*"))

    def parseUserClassPath(self, cpOption):
        from classpath.entry import Entry
        cpOption = cpOption or "."
        self.user = Entry.newEntry(cpOption)

    def readClass(self, className):
        className = className + ".class"
        return self.boot.readClass(className)[0] or self.ext.readClass(className)[0] or self.user.readClass(className)[0]

    @staticmethod
    def parse(jreOption, cpOption):
        clsPath = ClassPath()
        clsPath.parseBootAndExtClassPath(jreOption)
        clsPath.parseUserClassPath(cpOption)
        return clsPath


if __name__ == '__main__':
    clazzPath = ClassPath.parse("", "")
    print(clazzPath.readClass("System"))
